import axios from 'axios'



// axios请求拦截器
axios.interceptors.request.use(function(config) {
    // 从sessionStorage里取出token
    const token = window.sessionStorage.getItem('token');
    // 把token塞入Authorization里
    config.headers.Authorization = token;
    console.log(config)
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
)

// axios响应拦截器
axios.interceptors.response.use(function(response) {
    // 获取更新的token
    const {
      authorization
    } = response.headers;
    // 如果token存在则存在sessionStorage
    authorization && window.sessionStorage.setItem('token', authorization);
    return response;
  },
  function(error) {
    if (error.response) {
      const {
        status
      } = error.response;
      // 如果401或405则到登录页
      if (status === 401 || status === 405) {
        history.push('/login');
      }
    }
    return Promise.reject(error);
  }
)

export default axios
